//检查信息
function checkTemplate() {

    var result = "";
    //模板详情
    var content = $(".proBody").html();
    if(content == null || content.length == 0)
        {
        result += 'fail';
        $('.tiptemDetail').html("* 必填！").css("color", "red");
    } else {
        $('.tiptemDetail').html("√").css("color", "green");
    }
    //模板功效
    if ($.trim($('.temEffect').val()).length == 0) {
        result += 'fail';
        $('.tiptemEffect').html("* 必填！").css("color", "red");
    } else {
        $('.tiptemEffect').html("√").css("color", "green");
    }
    //模板说明
    if ($.trim($('.temInstruct').val()).length == 0) {
        result += 'fail';
        $('.tiptemInstruct').html("* 必填！").css("color", "red");
    } else {
        $('.tiptemInstruct').html("√").css("color", "green");
    }
    //是否通过
    if (result != "") {
        return false;
    }
    return true;
}

//初始化商品请求
$(function () {
    $.ajax({
        type: "POST",
        url: "/templateEntryController/findProducttmp",
        dataType: "json",
        async: false,
        success: function (data) {
            for (var i = 0; i < data.productList.length; i++) {
                $("#temDetail").append("<option value=" + data.productList[i].productId + ">" + data.productList[i].reserve1 + "</option>");
            }
            temDetail();
        },
        error: function () {

        }
    });
});

/**
 * 修改商品的数量时触发的事件
 * @param obj
 */
function changeProNum(obj) {
        var data_pid1 = obj.getAttribute("data-pid");
        var data_num1 = $(obj).val();
        var tarray = $('.templat-value');
        for (var i = 0; i < tarray.length; i++) {
            var  data_pid = tarray[i].getAttribute("data-pid");
            if (data_pid ==data_pid1){
               tarray[i].setAttribute("data-num",data_num1);
            }
        }
    getLocalStorg();
}

/**
 * 修改商品价格时触发的事件
 * @param obj
 */
function changeProPrice(obj) {
    var data_pid1 = obj.getAttribute("data-pid");
    var data_price = $(obj).val();
    var tarray = $('.templat-value');
    for (var i = 0; i < tarray.length; i++) {
        var  data_pid = tarray[i].getAttribute("data-pid");
        if (data_pid ==data_pid1){
            tarray[i].setAttribute("data-price",data_price);
        }
    }
    getLocalStorg();
}


/**
 * 统计价格
 */
function countPrice() {
    var count =0;
    var tmp;
    var val = $('input:radio[name="temType"]:checked').val();
    if (val == "dietary"){
        tmp =JSON.parse( localStorage.getItem("productTemplate"));
        if (tmp != null && tmp != undefined && tmp != '') {
            for (var i =0;i< tmp.length;i++){
                count += tmp[i].productCount * tmp[i].price;
            }
        }
    }else {
        tmp =JSON.parse( localStorage.getItem("acupTemplate"));
        if (tmp != null && tmp != undefined && tmp != '') {
            for (var i =0;i< tmp.length;i++){
                count += tmp[i].productCount * tmp[i].price;
            }
        }
    }
    $('#temProductPrice').val(count);
}


function getLocalStorg() {
    var tarray = $('.templat-value');
    var tempArra = new Array();
    for (var i = 0; i < tarray.length; i++) {
        console.log(tarray[i]);
        var  data_pid = tarray[i].getAttribute("data-pid");
        var data_num = tarray[i].getAttribute("data-num");
        var data_price = tarray[i].getAttribute("data-price");
        tempArra.push({Reid:data_pid,productCount:data_num,price:data_price});
        console.log(data_pid);
    }
    var val = $('input:radio[name="temType"]:checked').val();
    if (val == "dietary"){
        localStorage.setItem("productTemplate",JSON.stringify(tempArra));
    }else {
        localStorage.setItem("acupTemplate",JSON.stringify(tempArra));
    }
    countPrice();
}




function temDetail() {
    var tag_arr = "";
// 选择下拉框改变事件
    $("#temDetail").on("change", function () {
        $(".proBody").empty();
        console.log("改变事件");
        var tags = $(".am-selected-status").html();
        tag_arr = tags.split(",");
        // 遍历是否已选择
        for (var i = 0; i < tag_arr.length; i++) {
            if (tag_arr[i] == "点击选择...") {
                $(".proBody").empty();
                return false;
            }
            var idarr = $(this).val();
            // 遍历选中的id数组

            var Url='';
            var val = $('input:radio[name="temType"]:checked').val();
            if (val == "dietary"){
                localStorage.removeItem("acupTemplate");
                Url="/templateEntryController/findOneProduct?&proid=";
            }else {
                localStorage.removeItem("productTemplate");
                Url="/templateEntryController/findOneAcupuncturePoint?&acupid=";
            }
                for (var i = 0; i < idarr.length; i++) {
                var id = parseInt(idarr[i]);
                // 根据id，查询当前商品的所有信息
                $.ajax({
                    type: "GET",
                    url:  Url+ id,
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        console.log("请求数据");
                        console.log(data);
                        var strInfo ='';
                        if (val == "dietary"){
                           strInfo=  '<div class="am-btn am-btn-secondary am-round  " style="margin: 2px;"><input class="templat-value" type="hidden" data-pid="'+data.pro.productId+'" data-num="1" data-price="'+data.pro.unitPrice+'"><span>'
                               + data.pro.reserve1 +
                               '</span><input data-pid="'+data.pro.productId+'" type="text" value="1" onchange="changeProNum(this)" class="idList"  style="width:60px;height:25px;display:inline-block;vertical-align:top;">'
                               + data.pro.measureWay + "/" + "单价" + '<input type="text" onchange="changeProPrice(this)" data-pid="'+data.pro.productId+'" value=' + data.pro.unitPrice + ' style="width:60px;height:25px;display:inline-block;vertical-align:top;" class="unitPrice">' + ' 元' + '</div>';
                        }else {
                            strInfo=  '<div class="am-btn am-btn-secondary am-round" style="margin: 2px;"><input class="templat-value" type="hidden" data-pid="'+data.acup.acupId+'" data-num="1" data-price="20"><span>'
                                + data.acup.acupName +
                                '</span><input type="text" value="1" class="idList" data-pid="'+data.acup.acupId+'" onchange="changeProNum(this)" style="width:60px;height:25px;display:inline-block;vertical-align:top;">'
                                + "次"+ "/" + "单价" + '<input type="text" data-pid="'+data.acup.acupId+'" onchange="changeProPrice(this)" value="' + 20 + '" style="width:60px;height:25px;display:inline-block;vertical-align:top;" class="unitPrice">' + ' 元' + '</div>';
                        }

                        $(".proBody").append(strInfo);
                        /****************初始化计算总价****************/
                        /*商品*/

                        // 存放总价
                        getLocalStorg();
                        /****************失去焦点计算总价****************/
                        $(".idList").on("change", function () {
                            // 判断输入的值是否合法
                            var reg = /^\+?[1-9]\d*$/;
                            if (!reg.test($(this).val())) {
                                alert("商品只能是大于0的整数！默认为数量为1");
                                $(this).val(1);
                                changeProNum(this);
                                getLocalStorg();
                                return false;
                            }
                        });

                        $(".unitPrice").on("change", function () {
                            // 判断输入的值是否合法
                            console.log(this.getAttribute("value"));
                            var reg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
                            if (!reg.test($(this).val())) {
                                alert("商品价格只能为数字");
                                $(this).val(100);
                                changeProPrice(this);
                                getLocalStorg();
                                return false;
                            }
                        });
                        getLocalStorg();
                    },
                    error: function () {
                        alert("根据id，查询当前商品的所有信息失败！");
                    }
                });
            }

        }
    });
}




$(".temType").on("click", function () {

    var val = $('input:radio[name="temType"]:checked').val();
    if (val == "dietary") {

        //初始化商品请求
        $("#temDetail").empty();
        $("#proBody").empty();
        $(".temSumPrice").attr("value", "");
        $(function () {
            console.log("----------事件触发-------------------");
            $.ajax({
                type: "POST",
                url: "/templateEntryController/findProducttmp",
                dataType: "json",
                async: false,
                success: function (data) {
                    console.log(data);
                    for (var i = 0; i < data.productList.length; i++) {
                        $("#temDetail").append("<option value=" + data.productList[i].productId + ">" + data.productList[i].reserve1 + "</option>");
                    }
                },
                error: function () {
                    console.log("----出错了-----");
                }
            });
            temDetail();
        });

    } else {
        /**********************穴位选择*************************/
        $("#temDetail").empty();
        $(".proBody").empty();
        $(".purchPrice").val("");
        //初始穴位请求
        $(function () {
            $.ajax({
                type: "POST",
                url: "/templateEntryController/findAcupuncturePoint",
                dataType: "json",
                async: false,
                success: function (data) {
                    for (var i = 0; i < data.acupList.length; i++) {
                        $("#temDetail").append("<option value=" + data.acupList[i].acupId + ">" + data.acupList[i].acupName + "</option>");
                    }
                },
                error: function () {

                }
            });
            var tag_arr = "";
        // 选择下拉框改变事件
            $("#temDetail").on("change", function () {
                $(".proBody").empty();
                var tags = $(".am-selected-status").html();
                tag_arr = tags.split(",");
                // 遍历是否已选择
                for (var i = 0; i < tag_arr.length; i++) {
                    if (tag_arr[i] == "点击选择...") {
                        $(".proBody").empty();
                        return false;
                    }
                    var idarr = $(this).val();
                    var total = 0;
                    // 遍历选中的id数组
                    for (var i = 0; i < idarr.length; i++) {
                        var id = parseInt(idarr[i]);
                        // 根据id，查询当前商品的所有信息
                        $.ajax({
                            type: "GET",
                            url: "/templateEntryController/findOneAcupuncturePoint?&acupid=" + id,
                            dataType: "json",
                            async: false,
                            success: function (data) {
                                var val = $('input:radio[name="temType"]:checked').val();
                                var strInfo ='';
                                if (val == "dietary"){
                                    strInfo=  '<div class="am-btn am-btn-secondary am-round  " style="margin: 2px;"><input class="templat-value" type="hidden" data-pid="'+data.pro.productId+'" data-num="1" data-price="'+data.pro.unitPrice+'"><span>'
                                        + data.pro.reserve1 +
                                        '</span><input data-pid="'+data.pro.productId+'" type="text" value="1" onchange="changeProNum(this)" class="idList"  style="width:60px;height:25px;display:inline-block;vertical-align:top;">'
                                        + data.pro.measureWay + "/" + "单价" + '<input type="text" onchange="changeProPrice(this)" data-pid="'+data.pro.productId+'" value=' + data.pro.unitPrice + ' style="width:60px;height:25px;display:inline-block;vertical-align:top;" class="unitPrice">' + ' 元' + '</div>';
                                }else {
                                    strInfo=  '<div class="am-btn am-btn-secondary am-round" style="margin: 2px;"><input class="templat-value" type="hidden" data-pid="'+data.acup.acupId+'" data-num="1" data-price="20"><span>'
                                        + data.acup.acupName +
                                        '</span><input type="text" value="1" class="idList" data-pid="'+data.acup.acupId+'" onchange="changeProNum(this)" style="width:60px;height:25px;display:inline-block;vertical-align:top;">'
                                        + "次"+ "/" + "单价" + '<input type="text" data-pid="'+data.acup.acupId+'" onchange="changeProPrice(this)" value="' + 20 + '" style="width:60px;height:25px;display:inline-block;vertical-align:top;" class="unitPrice">' + ' 元' + '</div>';
                                }



                                $(".proBody").append(strInfo);

                                getLocalStorg();
                                /****************初始化计算总价****************/
                                    // 数量集合
                                /****************失去焦点计算总价****************/
                                $(".idList").on("change", function () {
                                    // 判断输入的值是否合法
                                    var reg = /^\+?[1-9]\d*$/;
                                    if (!reg.test($(this).val())) {
                                        alert("商品只能是大于0的整数！默认为数量为1");
                                        $(this).val(1);
                                        changeProNum(this);
                                        getLocalStorg();
                                        return false;
                                    }
                                    getLocalStorg();
                                });

                                /****************失去焦点计算总价****************/
                                $(".unitPrice").on("change", function () {
                                    // 判断输入的值是否合法
                                    var reg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
                                    if (!reg.test($(this).val())) {
                                        alert("价格只能是数字");
                                        $(this).val(100);
                                        changeProPrice(this);
                                        getLocalStorg();
                                        return false;
                                    }
                                    getLocalStorg();
                                });


                            },
                            error: function () {
                                alert("查询当前商品的所有信息失败！");
                            }
                        });
                    }

                }
            });
        });

    }
});


/**
 * 提交数据之前记得要清空本地存储
 */
//添加模板信息
document.getElementById("form_submit").addEventListener('click', function () {
        var form = document.getElementById("templateForm");
        var formData = new FormData(form);
        var tmp;
        var val = $('input:radio[name="temType"]:checked').val();
        if (val == "dietary"){
            tmp =localStorage.getItem("productTemplate");
        }else {
            tmp =localStorage.getItem("acupTemplate");
        }
        console.log(tmp);
        formData.set("temDetail",tmp);
        console.log(formData);
        if (confirm("您确定添加当前模板的数据？")) {
            formData.append("temEffect", $('.temEffect').val());
            formData.append("temInstruct",$('.temInstruct').val());
            formData.append("temSumPrice",$('#temProductPrice').val());
            var note =$('#temNote').val();
            if (note !=null && note != undefined && note != ''){
                formData.append("temNote",note);
            }
            if (checkTemplate()) {
                $.ajax({
                    type: "POST",
                    url: "/templateEntryController/addTemplate",
                    data: formData,
                    cache: false,
                    processData:false,
                    async: false,
                    contentType: false,
                    success: function (data) {
                        if (data.result) {
                            alert("添加成功！");
                            window.location.reload();
                        } else {
                            alert("添加失败！");
                        }
                    },
                    error: function () {
                        alert("发送请求失败！");
                    }
                });
            }
            else {
                alert("提交失败，请检查红色提示部分！");
        }
        }
    }
);

